export const HttpUtil = {
	getCode: response => response.data.code,
	getMessage: response => response.data.msg,
	getData: response => response.data.data,
	setData: (response, data) => {
		response.data.data = data;
	},
	getList: response => response.data.data.records,
	setList: (response, records) => {
		response.data.data.records = records;
	},
	getPageInfo: response => response.data.data,
	getHeaders: response => response.headers,
	getHeader: (response, headerName) =>
		response.headers[headerName.toLowerCase()],
	isOk: response => response.status === 200,
	isCreated: response => response.status === 201,
	isNoContent: response => response.status === 204,
	is2xx: response => response.status >= 200 && response.status < 300,
	isBadRequest: response => response.status === 400,
	isUnauthorized: response => response.status === 401,
	isForbidden: response => response.status === 403,
	isNotFound: response => response.status === 404,
	is4xx: response => response.status >= 400 && response.status < 500,
	is5xx: response => response.status >= 500 && response.status < 600,
	post: (url, params) => {
		const formElement = document.createElement('form');
		formElement.action = url;
		formElement.target = '_self';
		formElement.method = 'post';
		formElement.style.display = 'none';
		if (params) {
			Object.keys(params).forEach(value => {
				const opt = document.createElement('textarea');
				opt.name = value;
				opt.value = params[value];
				formElement.appendChild(opt);
			});
		}
		document.body.appendChild(formElement);
		formElement.submit();
		document.body.removeChild(formElement);
	},
	getParams: url => {
		const param = {};
		url.replace(/([^?&]+)=([^?&]+)/g, function(s, v, k) {
			const val = decodeURIComponent(k);
			const num = Number(val);
			if (isNaN(num)) {
				if (val === 'true') {
					param[v] = true;
				} else if (val === 'false') {
					param[v] = false;
				} else {
					param[v] = val;
				}
			} else {
				param[v] = num;
			}
			return k + '=' + v;
		});
		return param;
	},
	redirect: redirect => {
		window.location.href = redirect;
	},
	reload: () => {
		window.location.reload();
	},
	isExternal: path => {
		return /^(http:|https:|mailto:|tel:)/.test(path);
	}
};
